package com.gitee.cashzhang27.test.boot.functional.validator;

import com.gitee.cashzhang27.test.boot.functional.constraint.IdMustBeExist;
import com.gitee.cashzhang27.test.boot.functional.entity.Person;
import com.gitee.cashzhang27.test.boot.functional.service.PersonService;
import java.util.Optional;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Cash Zhang
 * @version v1.0 2020/09/16 18:05
 * @since v1.0
 */
public class MustBeExistValidator implements ConstraintValidator<IdMustBeExist, String> {

  @Autowired
  private PersonService personService;

  @Override
  public boolean isValid(String object, ConstraintValidatorContext constraintValidatorContext) {
    Person person = this.personService.getById(object);

    return !Optional.ofNullable(person).isPresent();
  }

}
